"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : Compatibility
Case Name   : 当前用户为有create role权限的用户，set password指定Sysadmin用户
Create At   : 2022/08/18
@zou_jialiang0501162243
Description :
        1.创建用户
        2.set password指定Sysadmin用户，replace使用正确的旧密码
        3.set password指定Sysadmin用户，不使用replace
        4.set password指定Sysadmin用户，replace使用错误的旧密码
        5.set password指定Sysadmin用户，新密码与旧密码相同
Expect      :
        1.用户创建成功
        2.报错
        3.报错
        4.报错
        5.报错
History     :
"""
import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class ClientConnection(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.common = Common()
        self.constant = Constant()
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.us_name1 = 'us_setpassword0012_01'
        self.us_name2 = 'us_setpassword0012_02'
        self.passwd1 = 'qwertyuiop'
        self.passwd2 = 'abcdefg'
        self.db_name = 'db_setpassword0012'
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        text1 = '--------修改密码复杂度策略   expect:修改成功--------'
        self.log.info(text1)
        self.pwd_1 = self.common.show_param('password_policy')
        res1 = self.sh_primary.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             'password_policy=0',
                                             single=True)
        self.log.info(res1)
        self.assertTrue(res1, '执行失败' + text1)
        text2 = '--------修改可重用天数为0   expect:修改成功--------'
        self.log.info(text2)
        self.pwd_2 = self.common.show_param('password_reuse_time')
        res2 = self.sh_primary.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             'password_reuse_time=0',
                                             single=True)
        self.log.info(res2)
        self.assertTrue(res2, '执行失败' + text2)
        text3 = '--------重启数据库   expect:重启成功--------'
        self.log.info(text3)
        res3 = self.sh_primary.restart_db_cluster()
        self.log.info(res3)
        self.assertTrue(res3, '执行失败' + text3)

    def test_set_password(self):
        text = '--------step1:创建用户和兼容b库   expect:创建成功--------'
        self.log.info(text)
        create_us1 = f"drop user if exists {self.us_name1};" \
                     f"create user {self.us_name1} password '{self.passwd1}';"
        create_us2 = f"drop user if exists {self.us_name2};" \
                     f"create user {self.us_name2} password '{self.passwd1}';"
        alter_us = f"alter user {self.us_name1} createrole;" \
                   f"grant all privileges to {self.us_name2};"
        res1 = self.sh_primary.execut_db_sql(sql=create_us1)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, res1, res1)
        res2 = self.sh_primary.execut_db_sql(sql=create_us2)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, res2, res2)
        res3 = self.sh_primary.execut_db_sql(sql=alter_us)
        for info in res3.splitlines():
            self.assertEqual(self.constant.ALTER_ROLE_SUCCESS_MSG, info, res3)
        create_db = f"drop database if exists {self.db_name};" \
                    f"create database {self.db_name} dbcompatibility='B';" \
                    f"\c {self.db_name}"
        res4 = self.sh_primary.execut_db_sql(create_db)
        self.log.info(res4)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, res4, res4)
        msg = f'You are now connected to database "{self.db_name}"'
        self.assertIn(msg, res4, '执行失败' + text)

        text = '--------step2:set password指定Sysadmin用户，replace使用正确的' \
               '旧密码   expect:报错--------'
        self.log.info(text)
        sql_cmd1 = f"set password for {self.us_name2} = '{self.passwd2}' " \
                   f"replace '{self.passwd1}';"
        msg1 = self.sh_primary.execut_db_sql(sql=sql_cmd1,
                                             sql_type=f'-U {self.us_name1} '
                                                      f'-W {self.passwd1}', 
                                             dbname=self.db_name)
        self.log.info(msg1)
        einfo = 'ERROR:  Permission denied.'
        self.assertEqual(einfo, msg1, msg1)

        text = '--------step3:set password指定Sysadmin用户，不使用replace   ' \
               'expect:报错--------'
        self.log.info(text)
        sql_cmd2 = f"set password for {self.us_name2} = '{self.passwd2}';"

        msg2 = self.sh_primary.execut_db_sql(sql=sql_cmd2,
                                             sql_type=f'-U {self.us_name1} '
                                                      f'-W {self.passwd1}', 
                                             dbname=self.db_name)
        self.log.info(msg2)
        self.assertEqual(einfo, msg2, msg2)

        text = '--------step4:set password指定Sysadmin用户，replace使用错误的' \
               '旧密码   expect:报错--------'
        self.log.info(text)
        sql_cmd3 = f"set password for {self.us_name2} = '{self.passwd1}' " \
                   f"replace '{self.passwd2}';"
        msg3 = self.sh_primary.execut_db_sql(sql=sql_cmd3,
                                             sql_type=f'-U {self.us_name1} '
                                                      f'-W {self.passwd1}', 
                                             dbname=self.db_name)
        self.log.info(msg3)
        self.assertEqual(einfo, msg3, msg3)

        text = '--------step5:set password指定Sysadmin用户，新密码与旧密码相同' \
               '   expect:报错--------'
        self.log.info(text)
        sql_cmd4 = f"set password for {self.us_name2} = '{self.passwd2}' " \
                   f"replace '{self.passwd2}';"
        msg4 = self.sh_primary.execut_db_sql(sql=sql_cmd4,
                                             sql_type=f'-U {self.us_name1} '
                                                      f'-W {self.passwd1}', 
                                             dbname=self.db_name)
        self.log.info(msg4)
        self.assertEqual(einfo, msg4, msg4)

    def tearDown(self):
        self.log.info('-----清理环境-----')
        text1 = '--------删除用户和兼容b库   expect:删除成功--------'
        self.log.info(text1)
        drop_cmd = f"drop user if exists {self.us_name1};" \
                   f"drop user if exists {self.us_name2};"
        res = self.sh_primary.execut_db_sql(drop_cmd)
        self.log.info(res)
        res0 = self.sh_primary.execut_db_sql(f"drop database if exists "
                                             f"{self.db_name};")
        self.log.info(res0)
        text2 = '--------恢复默认密码复杂度策略   expect:修改成功--------'
        self.log.info(text2)
        res1 = self.sh_primary.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'password_policy = {self.pwd_1}',
                                             single=True)
        self.log.info(res1)
        text3 = '--------恢复默认可重用天数   expect:修改成功--------'
        self.log.info(text3)
        res2 = self.sh_primary.execute_gsguc('set',
                                             self.constant.GSGUC_SUCCESS_MSG,
                                             f'password_reuse_time = '
                                             f'{self.pwd_2}',
                                             single=True)
        self.log.info(res2)
        text4 = '--------重启数据库   expect:重启成功--------'
        self.log.info(text4)
        res3 = self.sh_primary.restart_db_cluster()
        self.log.info(res3)
        for info in res.splitlines():
            self.assertEqual(self.constant.DROP_ROLE_SUCCESS_MSG, info,
                             '执行失败' + text1)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, res0,
                      '执行失败' + text1)
        self.assertTrue(res1, '执行失败' + text2)
        self.assertTrue(res2, '执行失败' + text3)
        self.assertTrue(res3, '执行失败' + text4)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')